package com.ld.security.common.core.util;

import cn.hutool.core.lang.Console;
import cn.hutool.extra.emoji.EmojiUtil;
import com.ld.security.common.core.anno.CrptKey;
import com.ld.security.common.core.anno.ScriptKey;
import com.ld.security.common.core.constant.CrptCondition;
import com.ld.security.common.core.exception.ApiException;
import lombok.SneakyThrows;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ScriptUtil {

    static ScriptEngine engine;

    static {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("javascript");
    }

    @SneakyThrows
    public static<E> E eval(String js){
        return (E)engine.eval(js);
    }

    /**
     * 对象处理
     * @param
     * @return
     */
    public static Object apply(Object obj){
        Map params =  ReflectionUtil.clone(obj,HashMap.class);
        for (Field field : ReflectionUtil.getAllDeclaredFields(obj.getClass())) {
            ScriptKey scriptKey = field.getAnnotation(ScriptKey.class);
            if(scriptKey == null){
                continue;
            }
            String js = TemplateUtil.renderString(scriptKey.value(),params);
            Object v =  eval(js);

            ReflectionUtil.invokeSetter(obj,field.getName(),v);
        }

        return obj;
    }




}
